import 'dart:convert';

import 'package:auto_route/annotations.dart';
import 'package:distribution_mall_flutter/constant/cf_constant.dart';
import 'package:distribution_mall_flutter/constant/constant.dart';
import 'package:distribution_mall_flutter/constant/point_constant.dart';
import 'package:distribution_mall_flutter/entity/address/address_entity.dart';
import 'package:distribution_mall_flutter/generated/l10n.dart';
import 'package:distribution_mall_flutter/mixins/page_stay_time.dart';
import 'package:distribution_mall_flutter/pages/address/address_area_select.dart';
import 'package:distribution_mall_flutter/pages/goods/product_details/product_details_provider.dart';
import 'package:distribution_mall_flutter/pages/home/home.dart';
import 'package:distribution_mall_flutter/router/route_utils.dart';
import 'package:distribution_mall_flutter/router/router.dart';
import 'package:distribution_mall_flutter/utils/common_third.dart';
import 'package:distribution_mall_flutter/utils/common_widget.dart';
import 'package:distribution_mall_flutter/utils/firebase/firebase_analytics_utils.dart';
import 'package:distribution_mall_flutter/utils/utils.dart';
import 'package:distribution_mall_flutter/widgets/click_dismiss.dart';
import 'package:distribution_mall_flutter/widgets/radio_list_tile.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_form_builder/flutter_form_builder.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:form_builder_validators/form_builder_validators.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:phone_numbers_parser/phone_numbers_parser.dart';

enum AddressActionType { add, edit }

@RoutePage<AddressItem>()
class AddressCreateEditPage extends StatefulHookConsumerWidget {
  final String? selectItem;
  final String type;

  const AddressCreateEditPage({
    super.key,
    @pathParam required this.type,
    @pathParam this.selectItem,
  });

  @override
  ConsumerState<AddressCreateEditPage> createState() =>
      _AddressCreateEditPageState();
}

class _AddressCreateEditPageState extends ConsumerState<AddressCreateEditPage>
    with PageStayTime<AddressCreateEditPage> {
  String? city, province, district, street, virtualPostcode;
  bool isSelect = false;
  late TextEditingController addressEditingController;
  bool isDef = false;
  bool isLoading = false;
  AddressItem? selectItem;
  final _formKey = GlobalKey<FormBuilderState>();
  @override
  String pageStayName = RouteInfoEnum.addressCreateEdit.routeZhName;

  @override
  void initState() {
    super.initState();
    if (widget.selectItem != null) {
      selectItem = AddressItem.fromJson(jsonDecode(widget.selectItem!));
    }
    city = selectItem?.city;
    province = selectItem?.province;
    district = selectItem?.district;
    street = selectItem?.street;
    isSelect = selectItem?.isDef ?? false;
    virtualPostcode = selectItem?.virtualPostcode;
    addressEditingController = TextEditingController(
        text: selectItem == null
            ? null
            : [province, city, district, street].join('/'));
  }

  @override
  popCallBack() {
    if (AddressActionType.add.name == widget.type) initPageStayTime();
  }

  @override
  Widget build(BuildContext context) {
    AddressActionType type = AddressActionType.values.byName(widget.type);
    ref.watch(userAddressProvider);
    final DateTime startTime = DateTime.now();

    return ClickDisMiss(
      child: Scaffold(
        appBar: AppBar(
          leading: CommonBtnWidget.arrowBack(
            onPressed: () {
              RouteUtils.back();
              // RouteUtils.onStoreDialogStayTime(
              //   name: PointDialogNameConstant.pdAddressAdd,
              //   startTime: startTime,
              //   endTime: DateTime.now(),
              // );
            },
            icon: Icons.arrow_back,
          ),
          title: Text(type == AddressActionType.add
              ? S.current.address_add
              : S.current.edit_add),
        ),
        bottomNavigationBar: Container(
            height: 42,
            margin: const EdgeInsets.only(bottom: 19, left: 24, right: 24),
            width: double.infinity,
            child: ElevatedButton.icon(
                icon: isLoading
                    ? const CupertinoActivityIndicator(
                        radius: 24 * 0.4,
                        color: ColorConstant.grey156,
                      )
                    : null,
                onPressed: () {
                  // _formKey.currentState?.saveAndValidate();
                  if (_formKey.currentState?.validate() == true) {
                    _formKey.currentState?.save();
                    Map<String, dynamic>? map = _formKey.currentState?.value;
                    if (map == null) return;
                    isLoading = true;
                    setState(() {});
                    var params = {
                      ...map,
                      'country': NationCode.ph,
                      'virtualPostcode': virtualPostcode,
                      'city': city,
                      'province': province,
                      'district': district,
                      'street': street,
                      'isDef': isDef,
                      'phoneNumber': Utils.addPrePhone(map['phone']),
                      if (type == AddressActionType.edit)
                        'distributorAddressId': selectItem!.distributorAddressId
                    };
                    ref
                        .read(userAddressProvider.notifier)
                        .createAndEditAddress(params, type)
                        .then((item) {
                      FirebaseAnalyticsUtils.logEvent(
                          name: PointConstant.addressSave,
                          parameters: {
                            'success': item == null ? 0 : 1,
                          });
                      if (item == null) return;
                      // if (type == AddressActionType.add) {
                      //   RouteUtils.onStoreDialogStayTime(
                      //     name: PointDialogNameConstant.pdAddressAdd,
                      //     startTime: startTime,
                      //     endTime: DateTime.now(),
                      //   );
                      // }

                      EPToast.showToast(S.current.save_successfully);
                      ref.read(userAddressProvider.notifier).initData();
                      Future.delayed(const Duration(seconds: 1), () {
                        print('item返回谁${item}');
                        appRouter.maybePop(AddressItem.fromJson(item.toJson()));
                      });
                    }).whenComplete(() {
                      Future.delayed(const Duration(milliseconds: 2000), () {
                        isLoading = false;
                        setState(() {});
                      });
                    });
                  }
                },
                label: Text(S.current.Save))),
        body: Container(
          padding: const EdgeInsets.only(left: 24, right: 24),
          decoration: const BoxDecoration(
            border: Border(
                top: BorderSide(
                    color: ColorConstant.grey233,
                    width: 0.9,
                    style: BorderStyle.solid)),
          ),
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  margin: const EdgeInsets.only(top: 24),
                  child: FormBuilder(
                    key: _formKey,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        renderInput(S.current.NAME, 'recipientName',
                            controller: useTextEditingController(
                                text: selectItem?.recipientName ?? ''),
                            hintText: S.current.address_pleaese_name,
                            validatorList: [
                              FormBuilderValidators.required(
                                  errorText: S.current.address_please_name)
                            ],
                            inputFormatterList: [
                              LengthLimitingTextInputFormatter(50)
                            ]),
                        renderInput(
                          S.current.phone_number,
                          'phone',
                          controller: useTextEditingController(
                              text: selectItem != null
                                  ? PhoneNumber.parse(selectItem!.phone ?? '')
                                      .nsn
                                  : null),
                          hintText: S.current.address_pleaese_phone,
                          inputFormatterList: [
                            LengthLimitingTextInputFormatter(11),
                            FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))
                          ],
                          validatorList: [
                            FormBuilderValidators.required(
                                errorText: S.current.address_please_phone),
                            FormBuilderValidators.match(RegularConstant.phpPhoe,
                                errorText:
                                    S.current.address_phone_error_format),
                          ],
                          keyboardType: TextInputType.number,
                          prefix: const SizedBox(
                            width: 40,
                            height: 43.7,
                            child: Align(
                              alignment: Alignment.center,
                              child: Text(
                                '+63',
                                style: TextStyle(
                                    color: Color.fromRGBO(119, 119, 119, 1),
                                    fontSize: FontConstant.f127,
                                    fontWeight: FontWeight.w500,
                                    letterSpacing: TextConstant.letterSpacing),
                              ),
                            ),
                          ),
                        ),
                        renderInput(S.current.ADDRESS, 'address',
                            hintText: S.current.address_pleaese_address,
                            readOnly: true,
                            bottomHeight: 10,
                            controller: addressEditingController,
                            suffixIcon: const Icon(
                              Icons.keyboard_arrow_right_outlined,
                              color: Color.fromRGBO(162, 162, 162, 1),
                            ),
                            validatorList: [
                              FormBuilderValidators.required(
                                  errorText: S.current.address_please_building),
                            ], onTap: () {
                          showModalBottomSheet(
                              context: context,
                              enableDrag: false,
                              isScrollControlled: true,
                              builder: (_) => AddressAreaSelect(
                                    callback: (list) {
                                      // LogUtil.d(list);
                                      // LogUtil.d(list.length);
                                      virtualPostcode =
                                          list.last.virtualPostcode;
                                      city = list[1].name;
                                      province = list[0].name;
                                      district = list[2].name;
                                      street = list[3].name;

                                      _formKey.currentState!.fields['address']!
                                          .didChange(list
                                              .map((e) => e.name)
                                              .join('/'));
                                      _formKey.currentState!.fields['zip']!
                                          .didChange(list.last.postcode ?? '');
                                      Navigator.pop(context);
                                    },
                                  ));
                        }),
                        renderInput(
                          '',
                          'detailInfo',
                          controller: useTextEditingController(
                              text: selectItem?.detailInfo ?? ''),
                          inputFormatterList: [
                            LengthLimitingTextInputFormatter(200)
                          ],
                          validatorList: [
                            FormBuilderValidators.required(
                                errorText: S.current.address_please_detailInfo),
                          ],
                          hintText: S.current.address_pleaese_default_address,
                        ),
                        renderInput(
                          S.current.POSTAL_CODE,
                          'zip',
                          controller: useTextEditingController(
                              text: selectItem?.zip ?? ''),
                          validatorList: [
                            FormBuilderValidators.required(
                                errorText: S.current.address_please_code),
                          ],
                          inputFormatterList: [
                            LengthLimitingTextInputFormatter(20)
                          ],
                          hintText: S.current.address_postal_code,
                        ),
                        EPRadioListTile(
                          commonWH: 21.8,
                          onChanged: (bool bol) {
                            isDef = bol;
                          },
                          isSelect: isSelect,
                        ),
                        const SizedBox(
                          height: 58.3,
                        )
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget renderInput(String label, String name,
      {required String hintText,
      Widget? prefix,
      Widget? suffixIcon,
      bool readOnly = false,
      TextEditingController? controller,
      List<TextInputFormatter>? inputFormatterList,
      required List<String? Function(String?)> validatorList,
      TextInputType keyboardType = TextInputType.name,
      double bottomHeight = EdgeConstant.edge218,
      GestureTapCallback? onTap}) {
    return Padding(
      padding: const EdgeInsets.only(
          // right: EdgeConstant.edge218,
          ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Visibility(
              visible: label.isNotEmpty,
              child: Text(
                '$label*',
                style: const TextStyle(
                    color: Colors.black,
                    fontSize: 14,
                    letterSpacing: TextConstant.letterSpacing,
                    fontWeight: FontWeight.w600),
              )),
          const SizedBox(
            height: 7.3,
          ),
          FormBuilderTextField(
              controller: controller,
              name: name,
              // maxLength: 50,
              onTap: onTap,
              cursorHeight: 20,
              readOnly: readOnly,
              autovalidateMode: AutovalidateMode.onUserInteraction,
              textAlignVertical: TextAlignVertical.center,
              inputFormatters: inputFormatterList,
              keyboardType: keyboardType,
              cursorColor: const Color.fromRGBO(119, 119, 119, 1),
              decoration: InputDecoration(
                // labelText: S.current.NAME,
                contentPadding: const EdgeInsets.symmetric(horizontal: 5),
                hintText: hintText,
                // isDense: true,
                prefixIcon: prefix,
                suffixIcon: suffixIcon,
                constraints: const BoxConstraints(
                  minHeight: 43.7,
                  maxHeight: 80,
                ),
                enabledBorder: const OutlineInputBorder(
                    borderSide:
                        BorderSide(color: ColorConstant.grey233, width: 0.9),
                    borderRadius: BorderRadius.all(
                        Radius.circular(RadiusConstant.edge10))),
                errorBorder: const OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Color.fromRGBO(255, 0, 0, 1), width: 0.9),
                    borderRadius: BorderRadius.all(
                        Radius.circular(RadiusConstant.edge10))),
                focusedErrorBorder: const OutlineInputBorder(
                    borderSide: BorderSide(
                        color: Color.fromRGBO(255, 0, 0, 0.7), width: 0.9),
                    borderRadius: BorderRadius.all(
                        Radius.circular(RadiusConstant.edge10))),
                focusedBorder: const OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.black, width: 0.9),
                    borderRadius: BorderRadius.all(
                        Radius.circular(RadiusConstant.edge10))),
                hintStyle: const TextStyle(
                  fontSize: FontConstant.f127,
                  color: Color.fromRGBO(119, 119, 119, 1),
                  textBaseline: TextBaseline.alphabetic, // 设置文本基线为基准线
                ),
              ),
              validator: FormBuilderValidators.compose(validatorList)),
          SizedBox(height: bottomHeight)
        ],
      ),
    );
  }
}
